import { Button, Image, Space, Tag, Typography, message } from "antd";
import { Iconify } from "@/components/icon";
import parse from "html-react-parser";
import { CopyOutlined } from "@ant-design/icons";

const getFileIcon = (mimetype: string) => {
	if (mimetype.startsWith("image/")) {
		return "eva:image-fill";
	}
	if (mimetype.startsWith("video/")) {
		return "eva:video-fill";
	}
	if (mimetype.startsWith("audio/")) {
		return "eva:music-fill";
	}
	if (mimetype === "application/pdf") {
		return "eva:file-text-fill";
	}
	if (mimetype === "application/msword") {
		return "eva:file-text-fill";
	}
	if (mimetype === "application/excel") {
		return "eva:file-text-fill";
	}
	if (mimetype.includes("zip") || mimetype.includes("rar")) {
		return "eva:archive-fill";
	}
	if (mimetype === "text/plain") {
		return "eva:file-text-fill";
	}
	return "eva:file-fill";
};

const getFileTypeFromUrl = (url: string) => {
	const extension = url.split(".").pop()?.toLowerCase();
	switch (extension) {
		case "jpg":
		case "jpeg":
		case "png":
		case "gif":
		case "webp":
			return "image/" + extension;
		case "mp4":
		case "webm":
			return "video/" + extension;
		case "mp3":
		case "wav":
			return "audio/" + extension;
		case "pdf":
			return "application/pdf";
		case "doc":
		case "docx":
			return "application/msword";
		case "xls":
		case "xlsx":
			return "application/excel";
		case "zip":
		case "rar":
			return "application/" + extension;
		case "txt":
			return "text/plain";
		default:
			return "application/octet-stream";
	}
};

/**
 * 将URL转换为Base64格式
 * @param url 图片URL
 * @returns Base64字符串
 */
const urlToBase64 = async (url: string): Promise<string> => {
	try {
		const response = await fetch(url);
		const blob = await response.blob();
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.onloadend = () => resolve(reader.result as string);
			reader.onerror = reject;
			reader.readAsDataURL(blob);
		});
	} catch (error) {
		console.error("转换图片失败:", error);
		return url;
	}
};

/**
 * 渲染不同类型的字段值
 * @param type 字段类型
 * @param value 字段值
 * @returns React节点
 */
export const renderFieldValue = (type: string, value: string) => {
	if (!value) {
		return "-";
	}

	switch (type) {
		case "text":
			return <Typography.Text>{value}</Typography.Text>;
		case "textarea":
			return <Typography.Paragraph>{value}</Typography.Paragraph>;
		case "richtext": {
			const copyHtml = async () => {
				try {
					const blob = new Blob([value], { type: "text/html" });
					const clipboardItem = new ClipboardItem({
						"text/html": blob,
						"text/plain": new Blob([value], { type: "text/plain" }),
					});
					await navigator.clipboard.write([clipboardItem]);
					message.success("HTML内容已复制");
				} catch (err) {
					// 如果高级API不支持，回退到基础复制
					try {
						await navigator.clipboard.writeText(value);
						message.success("HTML内容已复制");
					} catch (error) {
						message.error("复制失败");
					}
				}
			};

			// 处理图片预览
			const handleImagePreview = (e: React.MouseEvent<HTMLDivElement>) => {
				const target = e.target as HTMLElement;
				if (target.tagName === "IMG") {
					const img = target as HTMLImageElement;
					const previewInstance = Image.PreviewGroup.getInstance();
					if (previewInstance) {
						previewInstance.show(img.src);
					}
				}
			};

			// 使用html-react-parser解析富文本
			const parsedContent = parse(value, {
				replace: (domNode: any) => {
					if (domNode.type === "tag" && domNode.name === "img") {
						return (
							<Image
								src={domNode.attribs.src}
								alt={domNode.attribs.alt || ""}
								style={{
									maxWidth: "100px",
									height: "auto",
									cursor: "pointer",
								}}
								preview={{
									mask: null,
								}}
							/>
						);
					}
				},
			});

			return (
				<div style={{ position: "relative" }}>
					<div
						style={{
							width: "100%",
							border: "1px solid #f0f0f0",
							borderRadius: "4px",
							padding: "12px",
							marginBottom: "8px",
						}}
						onClick={handleImagePreview}
					>
						{parsedContent}
					</div>
					<Button
						type="text"
						icon={<CopyOutlined />}
						onClick={copyHtml}
						style={{
							position: "absolute",
							right: 0,
							top: 0,
							padding: "4px 8px",
						}}
						title="复制HTML内容"
					/>
				</div>
			);
		}
		case "number":
			return <Typography.Text>{value}</Typography.Text>;
		case "select":
			return <Tag color="blue">{value}</Tag>;
		case "radio":
			return <Tag color="blue">{value}</Tag>;
		case "checkbox":
			return (
				<Space wrap>
					{value.split(",").map((item) => (
						<Tag key={item} color="blue">
							{item}
						</Tag>
					))}
				</Space>
			);
		case "image":
			return (
				<Image.PreviewGroup>
					<Space wrap>
						{value.split(",").map((url) => (
							<Image
								key={url}
								src={url}
								alt=""
								style={{
									width: 120,
									height: 120,
									objectFit: "cover",
									borderRadius: "4px",
								}}
							/>
						))}
					</Space>
				</Image.PreviewGroup>
			);
		case "file": {
			return (
				<Space direction="vertical">
					{value.split(",").map((url) => {
						const mimetype = getFileTypeFromUrl(url);
						const isImage = mimetype.startsWith("image/");
						const filename = url.split("/").pop() || "";

						if (isImage) {
							return (
								<Image
									key={url}
									src={url}
									alt=""
									style={{
										width: 120,
										height: 120,
										objectFit: "cover",
										borderRadius: "4px",
									}}
								/>
							);
						}

						return (
							<Space key={url}>
								<div
									style={{
										width: "40px",
										height: "40px",
										display: "flex",
										alignItems: "center",
										justifyContent: "center",
										background: "#f5f5f5",
										borderRadius: "4px",
									}}
								>
									<Iconify icon={getFileIcon(mimetype)} size={24} />
								</div>
								<Typography.Link href={url} target="_blank">
									{filename}
								</Typography.Link>
							</Space>
						);
					})}
				</Space>
			);
		}
		default:
			return value;
	}
};
